package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseUIFragment;
import com.ouertech.android.agm.lib.ui.base.FragmentTabAdapter;
import com.ouertech.android.agm.lib.ui.base.UIOptions;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Category;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.GoodTopic;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.data.enums.EEventId;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.GoodsTopicListAdapter;
import com.simon.mengkou.ui.adapter.MallCategoryAdapter;
import com.simon.mengkou.ui.fragment.CategoryFragment;
import com.simon.mengkou.ui.fragment.ProductListFragment;
import com.simon.mengkou.ui.view.MyGridView;
import com.simon.mengkou.utils.UtilOuer;

import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiazhenshui on 16/7/23.
 * 商城界面
 */

public class MallFragment extends BaseUIFragment
        implements PullToRefreshBase.OnRefreshListener2<ListView>{

    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;

    @Bind(R.id.hot_sale_id_num)
    TextView mTvNum;

    private GoodsTopicListAdapter mAdapter;
    private int mPage = 0;

    //推荐商品
    SimpleDraweeView mSdvProduct;
    LinearLayout mLlGrRoot;
    TextView mTvTitle;
    TextView mTvTitleExt;
    TextView mTvPrice;
    TextView mTvMarketPrice;
    MyGridView mGgvCategory;
    MallCategoryAdapter mCategoryAdapter;

    private Product mProduct;


    @Override
    protected long initOptions() {
        return UIOptions.UI_OPTIONS_SYSTEMBAR
                | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM
                | UIOptions.UI_OPTIONS_CONTENT_CUSTOM;
    }


    @Override
    protected void initAppCustom() {
        setAppCustomLayout(R.layout.layout_mall_header);
    }


    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_pulltorefresh_list);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());

        registerAction(CstOuer.BROADCAST_ACTION.ADD_CART_ACTION);

        int num = OuerApplication.mPreferences.getCartProductNum();
        if(num == 0) {
            mTvNum.setVisibility(View.GONE);
        } else {
            mTvNum.setVisibility(View.VISIBLE);
            mTvNum.setText(String.valueOf(num));
        }

        View header = LayoutInflater.from(mActivity).inflate(R.layout.layout_category_header, null);
        mPtrView.getRefreshableView().addHeaderView(header);

        //推荐商品
        mLlGrRoot = (LinearLayout)header.findViewById(R.id.category_id_gr_root);
        mSdvProduct = (SimpleDraweeView) header.findViewById(R.id.category_id_image);
        mLlGrRoot.setOnClickListener(this);
        mTvMarketPrice = (TextView) header.findViewById(R.id.category_id_market_price);
        mTvPrice = (TextView)header.findViewById(R.id.category_id_price);
        mTvTitle = (TextView)header.findViewById(R.id.category_id_title);
        mTvTitleExt = (TextView)header.findViewById(R.id.category_id_title_ext);
        mGgvCategory = (MyGridView)header.findViewById(R.id.category_id_grid);

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        mAdapter = new GoodsTopicListAdapter(mActivity);
        mPtrView.setAdapter(mAdapter);



        mProduct = OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodRecommendCache.class)
                .getData();
        setGoodRecommendUI();

        List<Category> categories = OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallCategoryCache.class)
                .getData();
        mCategoryAdapter = new MallCategoryAdapter(mActivity);
        mGgvCategory.setAdapter(mCategoryAdapter);
        mCategoryAdapter.setList(categories);

        List<GoodTopic> datas = OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodsTopicCache.class)
                .getData();

        if(UtilList.isNotEmpty(datas)) {
            mAdapter.setList(datas);
            mPtrView.setTag(true);
            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPtrView.setTag(false);
            //首次失败重试
            setOnRetryListener(new OnRetryListener() {
                @Override
                public void onRetry() {
                    goodsRecommend();
                    getCategory();
                    getData(0, EDirection.REFRESH);
                }
            });


        }


        //获取数据
        goodsRecommend();
        getCategory();
        getData(0, EDirection.REFRESH);
        cartProductNum();
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.category_id_gr_root://打开商品详情
                if(mProduct != null) {
                    MobclickAgent.onEvent(mActivity, EEventId.MALL_RECOMMEND_PRODUCT);
                    OuerDispatcher.presentProductDetailActivity(mActivity, mProduct.getId());
                }
                break;
        }
    }

    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        String action = intent.getAction();
        if(CstOuer.BROADCAST_ACTION.ADD_CART_ACTION.equals(action)) {
            int num = intent.getIntExtra(CstOuer.KEY.CART_NUM, OuerApplication.mPreferences.getCartProductNum());
            if(num == 0) {
                mTvNum.setVisibility(View.GONE);
            } else {
                mTvNum.setVisibility(View.VISIBLE);
                mTvNum.setText(String.valueOf(num));
            }
        }
    }



    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getData(0, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getData(mPage + 1, EDirection.LOADMORE);
    }


    /**
     * 推荐商品
     */
    private void goodsRecommend() {
        AgnettyFuture future = OuerApplication.mOuerFuture.goodsRecommend(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mProduct = (Product) result.getAttach();
                        OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodRecommendCache.class)
                                .save(mProduct);
                        setGoodRecommendUI();
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }


    private void setGoodRecommendUI() {
        if(mProduct != null) {
            Image image = mProduct.getImageArray().get(0);
//                            if(image.getHeight() != 0 && image.getWidth() != 0) {
//                                mSdvProduct.setAspectRatio(image.getWidth() * 1f / image.getHeight());
//                            }

            OuerApplication.mImageLoader.loadImage(mSdvProduct, image.getUrl());

            if (UtilString.isNotBlank(mProduct.getTitleExt())) {
                mTvTitleExt.setText(mProduct.getTitleExt());
            } else {
                mTvTitleExt.setVisibility(View.GONE);
            }
            //商品标题
            mTvTitle.setText(mProduct.getTitle());
            //原价
            mTvMarketPrice.setText(getString(R.string.buy_recommend_market_price,
                    UtilOuer.formatPrice(mProduct.getMarketPrice())));

            mTvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中划线
            mTvMarketPrice.getPaint().setAntiAlias(true);
            //现价
            mTvPrice.setText(getString(R.string.buy_recommend_price,
                    UtilOuer.formatPrice(mProduct.getPrice())));
        }
    }


    /**
     * 获取购买分类
     */
    private void getCategory() {
        AgnettyFuture future = OuerApplication.mOuerFuture.buyCategory(
                new OuerFutureListener(mActivity) {


                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);

                        List<Category> categories = (List<Category>) result.getAttach();
                        OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallCategoryCache.class)
                                .save(categories);
                        mCategoryAdapter.setList(categories);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }



    private void getData(int page, final int direction) {
        //调用商品搜索接口
        AgnettyFuture future = OuerApplication.mOuerFuture.goodsTopicList(
                page, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(mActivity){

                    public void onStart(AgnettyResult result) {
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setLoading(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            mPtrView.setTag(true);
                            setLoading(false);
                        } else {
                            mPtrView.onRefreshComplete();
                        }

                        List<GoodTopic> datas = (List<GoodTopic>) result.getAttach();


                        if(direction == EDirection.REFRESH) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodsTopicCache.class)
                                    .save(datas);

                            mPage = 0;

                            if(UtilList.isEmpty(datas)) {
                                mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                                mAdapter.clearAll();
                            } else {
                                if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                    mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                                } else {
                                    mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
                                }

                                mAdapter.setList(datas);
                            }
                        } else {
                            if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }

                            mPage++;
                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 获取购物车商品数量
     */
    private void cartProductNum() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cartProductNum(null);
        attachDestroyFutures(future);
    }

    @OnClick(R.id.user_id_setting)
    public void goCart() {
        OuerDispatcher.presentCartActivity(mActivity);
    }

}
